{% extends 'base.html' %}
{% load static %}
{% load points_extras %}  {# 添加这一行 #}

{% block title %}{{ reward.name }} - Meet活动聚{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{% url 'home' %}">首页</a></li>
                    <li class="breadcrumb-item"><a href="{% url 'points:points_home' %}">我的积分</a></li>
                    <li class="breadcrumb-item"><a href="{% url 'points:rewards_shop' %}">积分商城</a></li>
                    <li class="breadcrumb-item active">{{ reward.name }}</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8">
            <!-- 奖品图片 -->
            <div class="card mb-4">
                {% if reward.image %}
                <img src="{{ reward.image.url }}" class="card-img-top" alt="{{ reward.name }}" style="max-height: 400px; object-fit: cover;">
                {% else %}
                <div class="card-img-top bg-light d-flex align-items-center justify-content-center" style="height: 300px;">
                    <i class="bi bi-gift text-muted display-1"></i>
                </div>
                {% endif %}
            </div>
        </div>

        <div class="col-md-4">
            <!-- 奖品信息 -->
            <div class="card">
                <div class="card-body">
                    <h3 class="card-title">{{ reward.name }}</h3>
                    <span class="badge bg-{% if reward.type == 'coupon' %}warning{% elif reward.type == 'privilege' %}info{% else %}success{% endif %} mb-3">
                        {{ reward.get_type_display }}
                    </span>

                    <div class="mb-3">
                        <h4 class="text-primary">{{ reward.points_required }} 积分</h4>
                    </div>

                    <div class="mb-3">
                        <strong>库存:</strong>
                        {% if reward.stock > 10 %}
                            <span class="text-success">充足</span>
                        {% elif reward.stock > 0 %}
                            <span class="text-warning">仅剩 {{ reward.stock }} 件</span>
                        {% else %}
                            <span class="text-danger">已售罄</span>
                        {% endif %}
                    </div>

                    <hr>

                    <!-- 奖品描述 -->
                    <div class="mb-4">
                        <h5>奖品描述</h5>
                        <p class="text-muted">{{ reward.description|linebreaks }}</p>
                    </div>

                    <!-- 兑换按钮 -->
                    <div class="d-grid gap-2">
                        {% if reward.stock > 0 %}
                            {% if user_points.available_points >= reward.points_required %}
                                <button type="button" class="btn btn-primary btn-lg" data-bs-toggle="modal" data-bs-target="#exchangeModal">
                                    <i class="bi bi-cart-check me-2"></i>立即兑换
                                </button>
                            {% else %}
                                <button class="btn btn-secondary btn-lg" disabled>
                                    <i class="bi bi-lock me-2"></i>积分不足
                                </button>
                                <small class="text-muted text-center">
                                    还差 {{ reward.points_required|subtract:user_points.available_points }} 积分
                                </small>
                            {% endif %}
                        {% else %}
                            <button class="btn btn-secondary btn-lg" disabled>
                                <i class="bi bi-x-circle me-2"></i>已售罄
                            </button>
                        {% endif %}
                    </div>

                    <!-- 用户积分信息 -->
                    <div class="mt-3 p-3 bg-light rounded">
                        <small class="text-muted">
                            <i class="bi bi-wallet2 me-1"></i>
                            您当前有 <strong>{{ user_points.available_points }}</strong> 积分可用
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 兑换确认模态框 -->
<div class="modal fade" id="exchangeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认兑换</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>您确定要兑换 <strong>{{ reward.name }}</strong> 吗？</p>
                <p>本次兑换将消耗 <span class="text-primary">{{ reward.points_required }}</span> 积分。</p>
                <p class="text-muted small">兑换后积分将立即扣除，奖品将进入您的兑换记录。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmExchange">确认兑换</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 兑换确认
    document.getElementById('confirmExchange').addEventListener('click', function() {
        const exchangeBtn = this;
        const originalText = exchangeBtn.innerHTML;

        // 显示加载状态
        exchangeBtn.innerHTML = '<i class="bi bi-arrow-repeat spinner-border spinner-border-sm me-2"></i>兑换中...';
        exchangeBtn.disabled = true;
        
        // 发送兑换请求
        fetch("{% url 'points:reward_exchange' reward.id %}", {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 兑换成功
                showAlert('兑换成功！请在兑换记录中查看详情。', 'success');
                setTimeout(() => {
                    window.location.href = "{% url 'points:exchange_history' %}";
                }, 1500);
            } else {
                // 兑换失败
                showAlert(data.message || '兑换失败，请重试', 'error');
                exchangeBtn.innerHTML = originalText;
                exchangeBtn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('网络错误，请重试', 'error');
            exchangeBtn.innerHTML = originalText;
            exchangeBtn.disabled = false;
        });
    });
    
    function showAlert(message, type) {
        // 创建提示框
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.querySelector('.container').prepend(alertDiv);
        
        // 自动隐藏
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 5000);
    }
});
</script>
{% endblock %}